package com.niit.mobileDevide.screenon;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;

public class ScreenOnMapper extends Mapper<LongWritable, Text, Text, ScreenOnBean> {

    private static final int USER_ID_INDEX = 0; // 用户ID索引
    private static final int SCREEN_ON_TIME_INDEX = 4; // 屏幕开启时间索引

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        if (key.get() == 0) return; // 忽略标题行

        String[] columns = value.toString().split(",");
        if (columns.length < 5) { // 确保至少有5个字段
            System.err.println("Skipping line due to insufficient fields: " + value);
            return;
        }

        try {
            // 提取用户ID
            String userId = columns[USER_ID_INDEX].trim();

            // 提取屏幕开启时间
            double screenOnTime = Double.parseDouble(columns[SCREEN_ON_TIME_INDEX].trim());

            // 写入键值对 (空字符串作为key, ScreenOnBean作为value)
            context.write(new Text(""), new ScreenOnBean(userId, screenOnTime));

        } catch (NumberFormatException e) {
            // 跳过格式错误的行，并打印错误信息
            System.err.println("Error parsing line: " + value + ". Error: " + e.getMessage());
        }
    }
}